<?php
namespace app\admin\controller;

use think\Request;
use think\Db;
use think\Controller;
use think\Config;

use Godok\Org\Auth;
use Godok\Org\Filter;

class Employee extends Base
{
	/**
     * 用户列表
     */
    // http://127.0.0.1/auth/User/index
    public function index()
    {
        
        $keywords = Request::instance()->param("keywords",'');
        $query= Db::name( 'employee' )
                ->field("id,username,name,nickname,avatar,phone,status,listorder")
                ->where('deleted',0)
                ->order('listorder asc');
        if ( !empty($keywords) ) {
            $query->where('name|nickname|phone', 'like', '%'.$keywords.'%');
        }
        $data['list'] = $query->paginate('',false,['query'=>Request()->param()]);
        
        foreach ($data['list'] as $key => $value) {
            $tmp = Db::connect([],'groups')->table('sdzx_employee_group')->alias('g')
            ->join('sdzx_employee_group_relation r','g.id=r.group_id')
            ->where("r.uid={$value['id']}")->select();

            $value['groups'] = $tmp;
            $data['list'][$key] = $value;
        }
        return $this->fetch('index',$data);
    }
    
    /**
     * 创建帐号
     * -----------------
     * /get  : view
     * -----------------
     * /post : insert 
     * @param ↓
     * $_POST[
     *  'username' => '用户名',
     *  'password' => '密码',
     *  'name'     => '真是姓名',
     *  'nickname' => '昵称',
     *  'avator'   => '头像url',
     *  'email'    => '电子邮箱',
     *  'phone'    => '手机号码',
     * ]
     * -----------------
     */
    // http://127.0.0.1/auth/User/add
    public function add()
    {
        if ( Request::instance()->isPost() ) {
            $data = Request::instance()->only('username,password,name,nickname,avator,email,phone,groups','post');
            if (!isset($data['username']) || empty(Filter::username($data['username'])) ) {
                $this->error('用户名格式错误！');
            }
            if ( isset($data['password']) && !empty(Filter::password($data['password'])) ) {
                $data['password'] = md5($data['password']);
            } else {
                $this->error('密码格式错误！');
            }
            if ( Db::name( 'employee' )->where('username',$data['username'])->find() ){
                $this->error('用户名已存在！');
            }
            //新增
            if ( !isset($data['avatar']) || empty($data['avatar']) ) {
                $data['avatar'] = Config::get('site.resource_url').'images/avatar/default.jpg';
            }
            if ( empty($data) ) {
                $this->error('创建失败！');
            }

            $groups = $data['groups']; unset($data['groups']);

            if (
                Db::name( 'employee' )
                ->insert($data)
            ) {
                $data['id'] = Db::name('employee_group')->getLastInsID();
                $tmp = [];
                foreach ($groups as $k => $v) {
                    $tmp[] = ['uid'=>$data['id'],'group_id'=>$v];
                }
                if ($tmp) {
                    Db::name('employee_group_relation')->insertAll($tmp);
                }
                $this->success('创建成功！','refresh');
            } else {
                $this->error('创建失败！');
            }
        } else {
            //用户类型
            $groups = Db::name('employee_group')->where(['status'=>1])->select();
            return $this->fetch('edit',['title'=>'用户信息','groups'=>$groups]);
        }
        
    }
    /**
     * 修改，内置管理员不能禁用
     * -----------------
     * /get  : view
     * -----------------
     * /post : update 
     * @$_POST[
     *  {
     *  'id'       => 'id',
     *  'username' => '用户名',
     *  'password' => '密码',
     *  'name'     => '真是姓名',
     *  'nickname' => '昵称',
     *  'avator'   => '头像url',
     *  'email'    => '电子邮箱',
     *  'phone'    => '手机号码',
     *  },{...},{...}
     * ]
     * -----------------
     * /call :
     * @param $id = int
     * @param $data = [
     *  'username' => '用户名',
     *  'password' => '密码',
     *  'name'     => '真是姓名',
     *  'nickname' => '昵称',
     *  'avator'   => '头像url',
     *  'email'    => '电子邮箱',
     *  'phone'    => '手机号码',
     * ]
     */
    public function edit($id='', $data = '')
    {
        if ( Request::instance()->isPost() ) {
            //do update
            if ( empty($id) ){
                $id = Request::instance()->get('id','','number_int');
            }
            
            if ( empty($id)  ){
                //批量修改
                $data = json_decode(file_get_contents('php://input'));
                if ( is_array($data) ){
                    foreach ( $data as $item ) {
                        if( is_object($item) && property_exists($item,'id') && !empty($item->id)) {
                            $column = [];
                            foreach (['username','password','name','nickname','avator','email','phone','status','listorder','groups'] as $key) {
                                if( property_exists($item,$key) ) {
                                    $column[$key] = $item->$key;
                                }
                            }
                            if ( !empty($column) ) {
                                $this->edit($item->id, $column);
                            }
                        } else {
                            $this->error('提交数据错误！');
                        }
                    }
                } else {
                    $this->error('提交数据错误！');
                }
                $this->success('修改成功！','refresh');
            } else {
                //修改单条
                if ( empty( $data) ) {
                    $data = Request::instance()->only('username,password,name,nickname,avator,email,phone,status,listorder,groups','post');
                }
                
                if ( isset($data['username']) && empty(Filter::username($data['username'])) ) {
                    $this->error('用户名格式错误！');
                }
                if (isset($data['password']) && !empty(Filter::password($data['password'])) ) {
                    $data['password'] = md5($data['password']);
                } elseif ( isset($data['password']) && !empty($data['password']) ) {
                    $this->error('密码格式错误！');
                } elseif (isset($data['password'])) {
                    unset($data['password']);
                }
                //判断用户名是否重复
                if (
                    isset($data['username'])
                    && Db::name( 'employee' )
                    ->where('username',$data['username'])
                    ->where('id', 'neq', $id)
                    ->find()
                ){
                    $this->error('用户名已存在！');
                }
                
                if ( empty($data) ) {
                    $this->error('提交的数据错误！');
                }

                if (isset($data['groups'])) {
                    $groups = $data['groups']; unset($data['groups']);
                }
                
                //更新数据库
                if (
                    Db::name( 'employee' )
                    ->where('id',$id)
                    ->update($data) !== false
                ) {
                    if ($groups) {
                        //先删除 权限
                        Db::name('employee_group_relation')->where(['uid'=>$id])->delete();
                        $tmp = [];
                        foreach ($groups as $k => $v) {
                            $tmp[] = ['uid'=>$id,'group_id'=>$v];
                        }
                        if ($tmp) {
                            Db::name('employee_group_relation')->insertAll($tmp);
                        }
                    }
                    $this->success('修改成功！','refresh');
                } else {
                    $this->error('修改失败！');
                }
            }
        } else {
            //get view
            $id = Request::instance()->get('id','','number_int');
            if ( empty($id) ){
                return '$_GET["id"]不能为空！';
            }
            $data = ['id'=>$id,'title'=>'用户信息'];
            $data['user'] = Db::name('employee')->where('id',$id)->find();
            //获取用户组信息
            $data['groups'] = self::getGroups($id);
            $data['groupname'] = '';
            if ( !empty( $data['groups'] ) ) {
            
                foreach( $data['groups'] as $group) {
                    $data['groupname'] .= '['.$group['title'].']';
                }
            
            }
            $data['user']['last_login_time'] = date('Y-m-d H:i:s',$data['user']['last_login_time']);
            $data['user']['groups'] = array_column($data['groups'], 'id');
            //用户类型
            $groups = Db::name('employee_group')->where(['status'=>1])->select();
            $data['groups'] = $groups;
            return $this->fetch('edit',$data);
        }
        
        
    }
    /**
     * 删除菜单
     * ---------------
     * @$_GET['id']
     */
    public function delete()
    {
        $request = Request::instance();
        $id = $request->post('id','');
    
        if ( empty($id) ) {
            return ['code'=>-1000, 'msg'=>'缺少参数！'];
        }
        if ( !is_array($id) ) {
            $id = [$id];
        }
        // if (in_array('1',$id)){
        //     return ['code'=>-1020, 'msg'=>'超级管理不能删除！'];
        // }
        if (
            Db::name( 'employee' )
            ->where('id', 'in', $id)
            ->update(['deleted'=>1])
        ) {
            return ['code'=>0, 'msg'=>'删除成功！'];
        } else {
            return ['code'=>-1010, 'msg'=>'删除失败！'];
        }
    }

    /**
     * 根据用户id获取用户组,返回值为数组
     * @param  $uid int     用户id ，默认是当前登录用户
     * @param  $onlyid boolen 是否只返回id,self::getGroupids()
     * @return array       用户所属的用户组 array(
     *              array('uid'=>'用户id','group_id'=>'用户组id','title'=>'用户组名称','rules'=>'用户组拥有的规则id,多个,号隔开'),
     *              ...)
     */
    public static function getGroups($uid = null, $onlyid = false)
    {
        $tmp = Db::connect([],'groups')->table('sdzx_employee_group')->alias('g')
            ->join('sdzx_employee_group_relation r','g.id=r.group_id')
            ->where("r.uid=$uid")->select();


        return $tmp;
    }
   
}